package com.infore.statisticsAndAlarm.service.impl;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.statisticsAndAlarm.bo.DatasChartsBo;
import com.infore.statisticsAndAlarm.constant.Constants;
import com.infore.statisticsAndAlarm.constant.ResultConstants;
import com.infore.statisticsAndAlarm.constant.VFiveLevelConstans;
import com.infore.statisticsAndAlarm.dto.WaterInstructionsDataDto;
import com.infore.statisticsAndAlarm.enums.ResultStatus;
import com.infore.statisticsAndAlarm.enums.WaterQualityTargetLevel;
import com.infore.statisticsAndAlarm.externalInterface.IDataReceivingService;
import com.infore.statisticsAndAlarm.externalInterface.IStieMangementService;
import com.infore.statisticsAndAlarm.outsideEntity.Project;
import com.infore.statisticsAndAlarm.repository.IDayDataRepository;
import com.infore.statisticsAndAlarm.repository.IMonthDataRepository;
import com.infore.statisticsAndAlarm.repository.IQuarterDataRepository;
import com.infore.statisticsAndAlarm.repository.IWeekDataRespository;
import com.infore.statisticsAndAlarm.repository.IYearDataRepository;
import com.infore.statisticsAndAlarm.select.util.PageObject;
import com.infore.statisticsAndAlarm.service.IDataCharsService;
import com.infore.statisticsAndAlarm.service.IWaterQualityEvaluationService;
import com.infore.statisticsAndAlarm.util.ArrayUtils;
import com.infore.statisticsAndAlarm.util.CookiesUtil;
import com.infore.statisticsAndAlarm.util.DateUtil;
import com.infore.statisticsAndAlarm.util.MyBeanUtils;
import com.infore.statisticsAndAlarm.util.ObjectMapperUtil;
import com.infore.statisticsAndAlarm.util.Page;
import com.infore.statisticsAndAlarm.util.PageUtil;
import com.infore.statisticsAndAlarm.util.ReflexUtil;
import com.infore.statisticsAndAlarm.util.ResultEntity;
import com.infore.statisticsAndAlarm.util.ScaleUtil;
import com.infore.statisticsAndAlarm.util.WaterLevelUtils;
import com.infore.statisticsAndAlarm.util.WaterQualityUtil;
import com.infore.statisticsAndAlarm.vo.ChartsVo;

@Service
public class WaterQualityEvaluationServiceImpl implements IWaterQualityEvaluationService {

	@Autowired
	private IDayDataRepository iDayDataRepository;
	@Autowired
	private IStieMangementService iStieMangementService;
	@Autowired
	private ObjectMapperUtil ObjectMapperUtil;
	@Autowired
	private IDataReceivingService iDataReceivingService;
	@Autowired
	private IMonthDataRepository iMonthDataRepository;
	@Autowired
	private WaterLevelUtils WaterLevelUtils;
	@Autowired
	private IDataCharsService iDataCharsService;
	@Autowired
	private IQuarterDataRepository iQuarterDataRepository;
	@Autowired
	private IYearDataRepository iYearDataRepository;
	@Autowired
	private IWeekDataRespository iWeekDataRespository;

	// 按时间段站点因子---分组得到数据
	public List<Map<String, Object>> datasCenter(String timeType, String startTime, String endTime,
			List<String> projectCodes, List<String> mnList) {
		Date startDate = new Date();
		Date endDate = new Date();
		List<Map<String, Object>> dataResults = new ArrayList<Map<String, Object>>();
		String codeString = StringUtils.join(projectCodes, ",");
		String stationMn = StringUtils.join(mnList, ",");
		switch (timeType) {
		case "real":
			// dateType:yyyy-MM-dd HH:ss:mm
			ResultEntity resntity = iDataReceivingService.realDataGroup(stationMn, codeString, startTime, endTime);
			if (resntity.getCode() != 0) {
				return dataResults;
			}
			dataResults = ObjectMapperUtil.convertListMap(resntity);
			break;
		case "hour":
			// dateType:yyyy-MM-dd HH:ss:mm
			if (startTime.length() > 14) {
				startTime = startTime.substring(0, 13) + ":00:00";
			}
			if (endTime.length() > 14) {
				endTime = endTime.substring(0, 13) + ":59:59";
			}
			ResultEntity resultEntity = iDataReceivingService.audioMoreReport(stationMn, codeString, startTime,
					endTime);
			if (resultEntity.getCode() != 0) {
				return dataResults;
			}
			dataResults = ObjectMapperUtil.convertListMap(resultEntity);
			break;
		case "day":
			// dateType:yyyy-MM-dd
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_STR);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_STR);
			dataResults = iDayDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		case "week":
			// dateType:yyyy-MM-dd
			String weekSatrt = startTime;
			String weekEnd = endTime;
			dataResults = iWeekDataRespository.audioMoreReport(weekSatrt, weekEnd, projectCodes, mnList);
			break;
		case "month":
			// dateType:yyyy-MM
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_YM);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_YM);
			dataResults = iMonthDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		case "quarter":
			// dateType:yyyyQ(年-季度)
			dataResults = iQuarterDataRepository.audioMoreReport(startTime, endTime, projectCodes, mnList);
			break;
		case "year":
			// dateType:yyyy
			dataResults = iYearDataRepository.audioMoreReport(startTime, endTime, projectCodes, mnList);
			break;
		default:
			// m默认查天表
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_STR);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_STR);
			dataResults = iDayDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		}
		return dataResults;
	}

	// 按单个站点mn时间段---不分组得到数据
	public List<Map<String, Object>> datasCenterSingle(String timeType, String startTime, String endTime,
			List<String> projectCodes, List<String> mnList) {
		Date startDate = new Date();
		Date endDate = new Date();
		List<Map<String, Object>> dataResults = new ArrayList<Map<String, Object>>();
		String codeString = StringUtils.join(projectCodes, ",");
		String stationMn = StringUtils.join(mnList, ",");
		switch (timeType) {
		case "real":
			ResultEntity resEntity = iDataReceivingService.realData(stationMn, codeString, startTime, endTime);
			if (resEntity.getCode() != 0) {
				return dataResults;
			}
			dataResults = ObjectMapperUtil.convertListMap(resEntity);
			break;
		case "hour":
			if (startTime.length() > 14) {
				startTime = startTime.substring(0, 13) + ":00:00";
			}
			if (endTime.length() > 14) {
				endTime = endTime.substring(0, 13) + ":59:59";
			}
			ResultEntity resultEntity = iDataReceivingService.audioSingReport(stationMn, codeString, startTime,
					endTime);
			if (resultEntity.getCode() != 0) {
				return dataResults;
			}
			dataResults = ObjectMapperUtil.convertListMap(resultEntity);
			break;
		case "day":
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_STR);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_STR);
			dataResults = iDayDataRepository.audioSingReport(startDate, endDate, projectCodes, mnList);
			break;
		case "month":
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_YM);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_YM);
			dataResults = iMonthDataRepository.audioSingReport(startDate, endDate, projectCodes, mnList);
			break;
		case "quarter":
			dataResults = iQuarterDataRepository.audioSingReport(startTime, endTime, projectCodes, mnList);
			break;
		case "year":
			dataResults = iYearDataRepository.audioSingleReport(startTime, endTime, projectCodes, mnList);
			break;
		default:
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_STR);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_STR);
			dataResults = iDayDataRepository.audioSingReport(startDate, endDate, projectCodes, mnList);
			break;
		}
		return dataResults;
	}

	// 多站点多因子站点mn时间段--分组得到数据
	public List<Map<String, Object>> datasCenterMore(String timeType, String startTime, String endTime,
			List<String> projectCodes, List<String> mnList) {
		Date startDate = new Date();
		Date endDate = new Date();
		List<Map<String, Object>> dataResults = new ArrayList<Map<String, Object>>();
		if (projectCodes == null || projectCodes.size() == 0 || mnList == null || mnList.size() == 0) {
			return dataResults;
		}
		switch (timeType) {
		case "hour":
			if (startTime.length() > 14) {
				startTime = startTime.substring(0, 13) + ":00:00";
			}
			if (endTime.length() > 14) {
				endTime = endTime.substring(0, 13) + ":59:59";
			}
			String codeString = StringUtils.join(projectCodes, ",");
			String stationMn = StringUtils.join(mnList, ",");
			ResultEntity resultEntity = iDataReceivingService.audioSingReport(stationMn, codeString, startTime,
					endTime);
			if (resultEntity.getCode() != 0) {
				return dataResults;
			}
			dataResults = ObjectMapperUtil.convertListMap(resultEntity);
			break;
		case "day":
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_STR);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_STR);
			dataResults = iDayDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		case "month":
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_YM);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_YM);
			dataResults = iMonthDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		case "quarter":
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_YM);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_YM);
			dataResults = iMonthDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		case "year":
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_YM);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_YM);
			dataResults = iMonthDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		default:
			startDate = DateUtil.stringToDate(startTime, DateUtil.DATE_SMALL_STR);
			endDate = DateUtil.stringToDate(endTime, DateUtil.DATE_SMALL_STR);
			dataResults = iDayDataRepository.audioMoreReport(startDate, endDate, projectCodes, mnList);
			break;
		}
		return dataResults;
	}

	@SuppressWarnings("unchecked")
	public ResultEntity qualityDetailsReports(String timeType, String startTime, String endTime, String queryCode,
			String queryType, PageObject pageObject, HttpServletRequest request) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();// 结果集
		List<WaterInstructionsDataDto> InstructionsList = new ArrayList<WaterInstructionsDataDto>();
		List<String> keyPollution = new ArrayList<String>();// 主要污染物
		Map<String, Object> resultMap = new HashMap<String, Object>();// 存储每一条数据
		Map<String, Object> valueMap = new HashMap<String, Object>();// 水质等级计算，存储记录类
		// 得到站点信息
		List<Map<String, Object>> stationList = new ArrayList<Map<String, Object>>();
		Map<String, List<Map<String, Object>>> groupList = new HashMap<String, List<Map<String, Object>>>();
		String platfrom = CookiesUtil.getCookieValue(request, "platformId");
		String appCode = CookiesUtil.getCookieValue(request, "appCode");
		String userId = CookiesUtil.getCookieValue(request, "userId");
		String admin = CookiesUtil.getCookieValue(request, "admin");
		ResultEntity stationResultEntity = iStieMangementService.queryStationInfoByCodes(queryCode, queryType, userId,
				platfrom, appCode, admin);
		if (stationResultEntity.getCode() == 0) {
			stationList = ObjectMapperUtil.getMapList(stationResultEntity);
			if (stationList == null || stationList.size() == 0) {
				return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
			}
			groupList = stationList.stream().collect(Collectors.groupingBy(x -> x.get("MN").toString()));
		}
		List<String> mnList = stationList.stream().map(l -> l.get("MN").toString()).collect(Collectors.toList());
		// 获得因子信息
		Map<String, Project> projectMap = null;
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mnList);
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		if (projectMap == null || projectMap.size() == 0) {
			return new ResultEntity().setDataList(list);
		}
		List<String> projectCodes = new ArrayList<>(projectMap.keySet());
		// 得到查询的数据集
		List<Map<String, Object>> dataResults = datasCenter(timeType, startTime, endTime, projectCodes, mnList);
		if (dataResults == null || dataResults.size() == 0) {
			return new ResultEntity().setDataList(list);
		}
		//
		int count = 0;
		for (Map<String, Object> dataResult : dataResults) {
			String mn = dataResult.get("MN") + "";
			String projectCode = dataResult.get("CODE") + "";
			String value = dataResult.get("VALUE") + "";
			Integer everyCount = dataResult.get("COUNT") == null ? 0 : Integer.parseInt(dataResult.get("COUNT") + "");
			String projectName = "";
			String decimalDigits = "3";
			if (projectMap != null) {
				Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(projectCode),
						Project.class);
				projectName = project.getProjectName();
				decimalDigits = project.getDecimalDigits();
			}
			value = ScaleUtil.sciCalProjectString(value, decimalDigits);// 数据修约
			// 站点信息
			List<Map<String, Object>> stationInfo = groupList.get(mn);
			String stationName = stationInfo.get(0).get("STATIONNAME") == null ? ""
					: stationInfo.get(0).get("STATIONNAME").toString();
			String areaName = stationInfo.get(0).get("AREANAME") == null ? ""
					: stationInfo.get(0).get("AREANAME").toString();
			String basinnName = stationInfo.get(0).get("BASINNNAME") == null ? ""
					: stationInfo.get(0).get("BASINNNAME").toString();
			String river = stationInfo.get(0).get("RIVER") == null ? "" : stationInfo.get(0).get("RIVER").toString();
			String armLevel = stationInfo.get(0).get("ARMLEVEL") == null ? ""
					: stationInfo.get(0).get("ARMLEVEL").toString();
			// 如果当前站点下没有因子相关信息，则创建新的，否则在原有的上追加
			if (!valueMap.containsKey(mn)) {
				count = 0;
				resultMap = new HashMap<String, Object>();
				keyPollution = new ArrayList<String>();
				WaterInstructionsDataDto Instructions = new WaterInstructionsDataDto();// 计算水质等级封装类
				ReflexUtil.setValue(Instructions, WaterInstructionsDataDto.class, projectCode, String.class, value);
				InstructionsList.add(Instructions);
				WaterQualityUtil.setWaterQuality(InstructionsList);
				String waterQuery = WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
				// String AimwaterQuery = armLevel;
				resultMap.put("mn", mn);
				resultMap.put("name", stationName);
				resultMap.put("level", waterQuery);
				// resultMap.put("waterCondition",
				// WaterLevelUtils.calculateProject(waterQuery));
				resultMap.put("armLevel", armLevel);
				resultMap.put("areaName", areaName);
				resultMap.put("river", river);
				resultMap.put("count", count + everyCount);
				resultMap.put("basinnName", basinnName);
				// 计算当前污染物是否超过三级
				if ((WaterQualityUtil.getWaterLevel(projectCode, value) > 3) && !keyPollution.contains(projectName)) {
					keyPollution.add(projectName);
				} // 计算设置主要污染物
				resultMap.put("keyPollution", StringUtils.join(keyPollution, ","));
				list.add(resultMap);
				valueMap.put(mn, Instructions);
			} else {
				WaterInstructionsDataDto Instructions = (WaterInstructionsDataDto) valueMap.get(mn);
				ReflexUtil.setValue(Instructions, WaterInstructionsDataDto.class, projectCode, String.class, value);
				WaterQualityUtil.setWaterQuality(InstructionsList);
				String waterQuery = WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
				resultMap.put("level", waterQuery);
				resultMap.put("count", count + everyCount);
				resultMap.put("basinnName", basinnName);
				// 计算当前污染物是否超过三级
				if ((WaterQualityUtil.getWaterLevel(projectCode, value) > 3) && !keyPollution.contains(projectName)) {
					keyPollution.add(projectName);
				}
				// 计算设置主要污染物
				resultMap.put("keyPollution", StringUtils.join(keyPollution, ","));
			}
		}
		// 添加因子值数据集中不存在的站点
		List<String> mnTotalStringList = list.stream().map(l -> l.get("mn").toString()).collect(Collectors.toList());// 结果集中的站点mn集合
		String mnTotalString = StringUtils.join(mnTotalStringList, "");// 转化成字符串
		for (String mn : mnList) {
			List<Map<String, Object>> stationInfo = groupList.get(mn);
			String stationName = stationInfo.get(0).get("STATIONNAME") == null ? ""
					: stationInfo.get(0).get("STATIONNAME").toString();
			String areaName = stationInfo.get(0).get("AREANAME") == null ? ""
					: stationInfo.get(0).get("AREANAME").toString();
			String basinnName = stationInfo.get(0).get("BASINNNAME") == null ? ""
					: stationInfo.get(0).get("BASINNNAME").toString();
			String river = stationInfo.get(0).get("RIVER") == null ? "" : stationInfo.get(0).get("RIVER").toString();
			String armLevel = stationInfo.get(0).get("ARMLEVEL") == null ? ""
					: stationInfo.get(0).get("ARMLEVEL").toString();
			if (!mnTotalString.contains(mn)) {
				Map<String, Object> mnMap = new HashMap<String, Object>();
				mnMap.put("mn", mn);// 站点mn
				mnMap.put("name", stationName);// 站点名称
				mnMap.put("keyPollution", "");// 主要污染物
				// mnMap.put("waterCondition", "");//
				mnMap.put("level", "");// 实际水质等级
				mnMap.put("areaName", areaName);// 区域名称
				mnMap.put("river", river);// 河流名称
				mnMap.put("armLevel", armLevel);// 区域流域目标水质等级
				mnMap.put("count", 0);// 总共记录条数
				mnMap.put("basinnName", basinnName);// 流域名称
				list.add(mnMap);
				mnTotalString = mnTotalString + mn;
			}
		}
		// 分页设置
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			Page<Map<String, Object>> page = PageUtil.inventedPage(list, pageObject);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
		} else {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
		}
	}

	public ResultEntity waterQualityPie(String timeType, String startTime, String endTime, String queryCode,
			String queryType, HttpServletRequest request) {
		//
		PageObject pageObject = null;
		// 得到数据结果集
		ResultEntity resultEntity = qualityDetailsReports(timeType, startTime, endTime, queryCode, queryType,
				pageObject, request);
		List<Map<String, Object>> list = ObjectMapperUtil.convertListMap(resultEntity);
		// 初始化echarts实体
		ChartsVo chartsVo = new ChartsVo();
		List<String> legend = new ArrayList<String>(); // 图例数据集
		List<Map<String, Object>> series = new ArrayList<Map<String, Object>>(); // 系列列表数据集
		Map<String, Object> seriesMap = new HashMap<String, Object>();
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		// 初始化数据全为null,并按顺序放到集合中
		for (WaterQualityTargetLevel e : WaterQualityTargetLevel.values()) {
			Map<String, Object> pieMap = new HashMap<String, Object>();
			if ("0".equals(e.getStatusCode()) || "1".equals(e.getStatusCode())) {
				continue;
			} else if ("2".equals(e.getStatusCode())) {
				pieMap.put("name", "I-II类");
				legend.add("I-II类");
				pieMap.put("value", null);
				data.add(pieMap);
			} else {
				pieMap.put("name", e.getReasonPhrase());
				pieMap.put("value", null);
				legend.add(e.getReasonPhrase());
				data.add(pieMap);
			}
		}
		seriesMap.put("data", data);
		series.add(seriesMap);
		// 根据水质类别对数据进行分组
		Map<String, List<Map<String, Object>>> groupList = list.stream()
				.filter(f -> !"".equals(f.get("level").toString()))
				.collect(Collectors.groupingBy(l -> l.get("level").toString()));
		// groupList.remove("");
		List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		groupList.forEach((k, klist) -> {
			String level = WaterLevelUtils.exchangeWaterLevelToNumber(k);
			Integer levelInteger = Integer.parseInt(level);
			int flag = 2;// 用来判断1-2级时，确保放在集合的第一位
			if (levelInteger == 1) {
				flag = 1;
			} else if (levelInteger == 2) {
				flag = 2;
			}
			// 根据集合中存放每类等级的下标与水质等级数字之间的关系（如果是1-2级别则下表差1，如果是其他级别则下标差2）
			Integer oldLevelNum = data.get(levelInteger - flag).get("value") == null ? 0
					: (Integer) data.get(levelInteger - flag).get("value");// 旧的水质级别数目
			Map<String, Object> pieMapSingle = data.get(levelInteger - flag);// 得到当前水质级别，并更新数目
			pieMapSingle.put("value", oldLevelNum + klist.size());
		});
		if (datas.size() > 0) {
			seriesMap.put("data", datas);
			seriesMap.put("name", "断面水质比例图");
			series.add(seriesMap);
		}
		chartsVo.setLegend(legend);
		chartsVo.setSeries(series);
		if (series == null || series.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(chartsVo);
	}

	@SuppressWarnings("unused")
	public ResultEntity waterQualityBarLine(String timeType, String startTime, String endTime, String queryCode,
			String queryType, HttpServletRequest request) {
		PageObject pageObject = null;
		// 得到数据结果集
		ResultEntity resultEntity = qualityDetailsReports(timeType, startTime, endTime, queryCode, queryType,
				pageObject, request);
		List<Map<String, Object>> list = ObjectMapperUtil.convertListMap(resultEntity);
		// 初始化echarts实体
		ChartsVo chartsVo = new ChartsVo();
		List<String> legend = new ArrayList<String>(); // 图例数据集
		List<String> xAxis = new ArrayList<String>();// x轴数据
		List<Map<String, Object>> series = new ArrayList<Map<String, Object>>(); // 系列列表数据集
		List<Map<String, Object>> stationList = new ArrayList<Map<String, Object>>();
		// 得到站点信息
		Map<String, List<Map<String, Object>>> groupList = new HashMap<String, List<Map<String, Object>>>();
		String platfrom = CookiesUtil.getCookieValue(request, "platformId");
		String appCode = CookiesUtil.getCookieValue(request, "appCode");
		String userId = CookiesUtil.getCookieValue(request, "userId");
		String admin = CookiesUtil.getCookieValue(request, "admin");
		ResultEntity stationResultEntity = iStieMangementService.queryStationInfoByCodes(queryCode, queryType, userId,
				platfrom, appCode, admin);
		if (stationResultEntity.getCode() == 0) {
			stationList = ObjectMapperUtil.getMapList(stationResultEntity);
			if (stationList == null || stationList.size() == 0) {
				return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
			}
			groupList = stationList.stream().collect(Collectors.groupingBy(x -> x.get("MN").toString()));
		}
		List<String> mnList = stationList.stream().map(l -> l.get("MN").toString()).collect(Collectors.toList());
		List<String> dataLevel = new ArrayList<String>();// 水质等级
		List<String> dataAimLevel = new ArrayList<String>();// 目标水质等级
		Map<String, Object> dataLevelMap = new HashMap<String, Object>(); // 水质等级数据集
		Map<String, Object> dataAimLevelMap = new HashMap<String, Object>(); // 目标水质等级数据集
		for (Map<String, Object> dataResult : list) {
			String level = dataResult.get("level") == null ? "" : dataResult.get("level").toString();// 水质等级
			String airmLevel = dataResult.get("armLevel") == null ? "" : dataResult.get("armLevel").toString();// 目标水质等级
			String name = dataResult.get("name") == null ? "" : dataResult.get("name").toString();// 断面名称
			xAxis.add(name);
			dataLevel.add(WaterLevelUtils.exchangeWaterLevelToNumber(level));
			dataAimLevel.add(WaterLevelUtils.exchangeWaterLevelToNumber(airmLevel));
			// 因为qualityDetailsReports方法已经对空战点进行了数据补齐，所以这里不需要再次补空
		}
		//
		legend.add("实际水质等级");
		legend.add("目标水质等级");
		dataLevelMap.put("name", "实际水质等级");
		dataLevelMap.put("value", dataLevel);
		dataAimLevelMap.put("name", "目标水质等级");
		dataAimLevelMap.put("value", dataAimLevel);
		series.add(dataLevelMap);
		series.add(dataAimLevelMap);
		chartsVo.setLegend(legend);
		chartsVo.setxAxis(xAxis);
		chartsVo.setSeries(series);
		if (series == null || series.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(chartsVo);
	}

	public ResultEntity waterQualitySummary(String timeType, String startTime, String endTime, String queryCode,
			String queryType, HttpServletRequest request) {
		// 得到区域/流域信息
		ResultEntity areaEntity = iStieMangementService.queryAreaByAreaCode(queryCode, queryType);
		List<Map<String, Object>> areaEntityMap = ObjectMapperUtil.convertListMap(areaEntity);
		Object areaNameObject = ("area").equals(queryType) ? areaEntityMap.get(0).get("areaName")
				: areaEntityMap.get(0).get("basinnName");
		String areaName = areaNameObject == null ? "" : areaNameObject.toString();
		String airLevel = areaEntityMap.get(0).get("aimWaterLevel") == null ? ""
				: areaEntityMap.get(0).get("aimWaterLevel").toString();
		String level = "";
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("airLevel", airLevel);
		// 得到数据结果集---用于比较水质等级
		PageObject pageObject = null;
		ResultEntity resultEntity = qualityDetailsReports(timeType, startTime, endTime, queryCode, queryType,
				pageObject, request);
		List<Map<String, Object>> list = ObjectMapperUtil.convertListMap(resultEntity);
		Map<String, List<Map<String, Object>>> groupList = new HashMap<String, List<Map<String, Object>>>();
		groupList = list.stream().filter(f -> !"".equals(f.get("level").toString()))
				.collect(Collectors.groupingBy(l -> l.get("level").toString()));
		// groupList.remove("");//剔除掉无数据的断面
		Double count = 0.0;// 用于计算当前水质--记录总数
		Map<String, Object> summaryMap = new HashMap<String, Object>();// 用于计算各类水质等级所占比例
		Map<Integer, String> countLevelMap = new HashMap<Integer, String>();// 计算当前水质情况
		for (Entry<String, List<Map<String, Object>>> map : groupList.entrySet()) {
			count += map.getValue().size();
			summaryMap.put(map.getKey(), map.getValue().size());
			countLevelMap.put(map.getValue().size(), map.getKey());
		}
		// 拼接总结语句
		NumberFormat format = NumberFormat.getPercentInstance();
		format.setMaximumFractionDigits(2);// 设置保留几位小数
		String message = "";// 返回总结语句信息
		if (count != 0.0) {
			Double one = summaryMap.get("I类") == null ? 0.0 : ((int) summaryMap.get("I类") / count);
			Double two = summaryMap.get("II类") == null ? 0.0 : ((int) summaryMap.get("II类") / count);
			String oneTwo = format.format((one + two));
			String three = summaryMap.get("III类") == null ? "0.00%"
					: format.format((int) summaryMap.get("III类") / count);
			String four = summaryMap.get("IV类") == null ? "0.00%" : format.format((int) summaryMap.get("IV类") / count);
			String five = summaryMap.get("V类") == null ? "0.00%" : format.format((int) summaryMap.get("V类") / count);
			String vFive = summaryMap.get("劣V类") == null ? "0.00%" : format.format((int) summaryMap.get("劣V类") / count);
			message = "水质概述：" + startTime + "至" + endTime + "," + areaName + "主要断面水质达到" + "Ⅰ~Ⅱ类占" + oneTwo + ",Ⅲ类占"
					+ three + ",Ⅳ类占" + four + ",Ⅴ类占" + five + ",劣Ⅴ类占" + vFive + "(共" + (int) (double) count + "个断面纳入计算"
					+ ")";
		}
		if (countLevelMap != null && countLevelMap.size() != 0) {
			int key = Collections.max(countLevelMap.keySet());// 对各类水质等级数目进行排序
			String countLevel = countLevelMap.get(key) == null ? "" : countLevelMap.get(key);// 最大比例的水质等级
			level = WaterLevelUtils.calculateProject(countLevel);
			result.put("level", level);// 实际水质状况(优良等）
		} else {
			result.put("level", "");// 实际水质状况(优良等）
		}
		result.put("computingMethod", "比例法");// 分析方法
		result.put("time", startTime + "至" + endTime);// 起止时间
		result.put("message", message);// 总结
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(result);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity waterQualityBarLineForMn(String timeType, String startTime, String endTime, String queryCode,
			String queryType, HttpServletRequest request) {
		// 最后返回结果集
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 站点集合
		List<String> mnList = ArrayUtils.stringToList(queryCode);
		ResultEntity stationAllEntity = iStieMangementService.queryAllInfoByMn(queryCode);
		List<Map<String, Object>> stationAllInfo = ObjectMapperUtil.convertListMap(stationAllEntity);
		// 查询单站点下因子code集合
		String stationMn = queryCode;
		ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(stationMn);
		List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
		List<Map<String, Object>> dataResults = datasCenterMore(timeType, startTime, endTime, projectCodes, mnList);
		if (dataResults == null || dataResults.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
		}
		// 获得因子信息
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mnList);
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		// 初始化echarts实体
		ChartsVo chartsVo = new ChartsVo();
		List<String> xAxis = new ArrayList<String>(); // X轴数据集
		List<String> legend = new ArrayList<String>(); // 图例数据集
		List<Map<String, Object>> series = new ArrayList<Map<String, Object>>(); // 系列列表数据集
		List<String> dataLevel = new ArrayList<String>();// 水质等级
		List<String> dataAimLevel = new ArrayList<String>();// 目标水质等级
		Map<String, Object> dataLevelMap = new HashMap<String, Object>(); // 水质等级数据集
		Map<String, Object> dataAimLevelMap = new HashMap<String, Object>(); // 目标水质等级数据集
		String stationLevel = stationAllInfo.get(0).get("targerWaterQuality") == null ? "III类"
				: stationAllInfo.get(0).get("targerWaterQuality").toString();
		stationLevel = WaterLevelUtils.exchangeWaterLevelToNumber(stationLevel);
		String value = "0";
		for (String code : projectCodes) {
			String projectName = "";// 因子名称
			if (projectMap != null) {
				Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(code),
						Project.class);
				projectName = project.getProjectName();
			}
			xAxis.add(projectName);// x周设置
			List<String> values = dataResults.stream().filter(x -> x.get("CODE").equals(code))
					.map(l -> l.get("VALUE").toString()).collect(Collectors.toList());
			if (values.size() > 0) {
				WaterInstructionsDataDto Instruc = new WaterInstructionsDataDto();
				List<WaterInstructionsDataDto> InstrucList = new ArrayList<WaterInstructionsDataDto>();
				ReflexUtil.setValue(Instruc, WaterInstructionsDataDto.class, code, String.class, values.get(0));
				InstrucList.add(Instruc);
				WaterQualityUtil.setWaterQuality(InstrucList);
				value = Instruc.getWaterQuality();// 实际水质等级用数字表示
			}
			dataLevel.add(value);
			dataAimLevel.add(stationLevel);
		}
		dataLevelMap.put("name", "实际水质等级");
		dataLevelMap.put("value", dataLevel);
		dataAimLevelMap.put("name", "目标水质等级");
		dataAimLevelMap.put("value", dataAimLevel);
		series.add(dataLevelMap);
		series.add(dataAimLevelMap);
		chartsVo.setLegend(legend);
		chartsVo.setxAxis(xAxis);
		chartsVo.setSeries(series);
		if (series == null || series.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(chartsVo);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity qualityDetailsReportsForMn(String timeType, String startTime, String endTime, String queryCode,
			String queryType, PageObject pageObject, HttpServletRequest request) {
		// 最后返回结果集
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 站点集合
		List<String> mnList = ArrayUtils.stringToList(queryCode);
		// 查询单站点下因子code集合
		String stationMn = queryCode;
		ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(stationMn);
		List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
		if (projectCodes == null || projectCodes.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
		}
		List<Map<String, Object>> dataResults = datasCenterSingle(timeType, startTime, endTime, projectCodes, mnList);
		if (dataResults == null || dataResults.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();// 存储每一条数据
		Map<String, Object> valueMap = new HashMap<String, Object>();// 水质等级计算，存储记录类
		List<WaterInstructionsDataDto> InstructionsList = new ArrayList<WaterInstructionsDataDto>();
		// 获得因子信息
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mnList);
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		// 遍历因子值数据集，设置相关的值
		for (Map<String, Object> dataResultMap : dataResults) {
			String time;
			if ("hour".equals(timeType) || "real".equals(timeType)) {
				// 远程调用小时数据接口时，服务间调用会将时间类型转化成字符串
				// 截取格林尼治时间为标准时间
				String indexStrings = dataResultMap.get("TIME").toString();
				time = indexStrings.substring(0, 10) + " " + indexStrings.substring(11, 19);
			} else if ("week".equals(timeType)) {
				time = DateUtil.dateToString((Date) (dataResultMap.get("TIME")), DateUtil.DATE_SMALL_STR);
				time = DateUtil.getMonthWeekString(time);
			} else if ("year".equals(timeType)) {
				time = dataResultMap.get("TIME").toString();
			} else if ("month".equals(timeType)) {
				time = DateUtil.dateToString((Date) (dataResultMap.get("TIME")), DateUtil.DATE_SMALL_YM);
			} else if ("quarter".equals(timeType)) {
				time = dataResultMap.get("TIME").toString();
			} else {
				time = DateUtil.dateToString((Date) (dataResultMap.get("TIME")), DateUtil.DATE_SMALL_STR);
			}
			String projectCode = dataResultMap.get("CODE").toString();
			String value = dataResultMap.get("VALUE").toString();
			String projectUnit = "";
			String projectName = "";
			String decimalDigits = "3";
			if (projectMap != null) {
				Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(projectCode),
						Project.class);
				projectUnit = project.getProjectUnit();
				projectName = project.getProjectName();
				decimalDigits = project.getDecimalDigits();
			}
			value = ScaleUtil.sciCalProjectString(value, decimalDigits);// 数据修约
			resultMap = new HashMap<String, Object>();
			WaterInstructionsDataDto Instructions = new WaterInstructionsDataDto();// 计算水质等级封装类
			ReflexUtil.setValue(Instructions, WaterInstructionsDataDto.class, projectCode, String.class, value);
			InstructionsList.add(Instructions);
			WaterQualityUtil.setWaterQuality(InstructionsList);
			String waterLevel = WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
			String Vlevel = VFiveLevelConstans.projectWaterQuality.get(projectCode) == null ? ""
					: VFiveLevelConstans.projectWaterQuality.get(projectCode).get(4).toString();
			resultMap.put("time", time);// 设置时间
			resultMap.put("name", projectName);// 因子名称
			resultMap.put("value", value);// 因子编号和因子值
			resultMap.put("level", waterLevel);// 实际水质等级
			resultMap.put("unit", projectUnit);// 因子编号和因子单位
			resultMap.put("Vlevel", Vlevel);// 因子编号和因子单位
			list.add(resultMap);
			valueMap.put(projectCode + time, Instructions);
		}
		// 分页设置
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			Page<Map<String, Object>> page = PageUtil.inventedPage(list, pageObject);
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setPage(page);
		} else {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setDataList(list);
		}
	}

	public ResultEntity waterQualityLines(String timeType, String startTime, String endTime, String queryCode,
			String queryType, HttpServletRequest request) {
		// 调用多站多因子查询接口
		String stationMn = queryCode;
		ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(stationMn);
		List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
		DatasChartsBo bo = new DatasChartsBo();
		if (startTime.length() > 14) {
			startTime = startTime.substring(0, 13) + ":00:00";
		}
		if (endTime.length() > 14) {
			endTime = endTime.substring(0, 13) + ":59:59";
		}
		bo.setStartTime(startTime);
		bo.setEndTime(endTime);
		bo.setType(timeType);
		bo.setStationCode(queryCode);
		bo.setFactorCode(StringUtils.join(projectCodes, ","));
		if (projectCodes == null || projectCodes.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, ResultConstants.NO_PROJECT);
		}
		return iDataCharsService.singleDatasCharts(bo);
	}

	@SuppressWarnings("unchecked")
	public ResultEntity waterQualitySummaryMn(String timeType, String startTime, String endTime, String queryCode,
			String queryType, HttpServletRequest request) {
		List<String> mnList = ArrayUtils.stringToList(queryCode);
		Map<String, Object> info = new HashMap<String, Object>();// 返回结果集
		Map<String, Object> result = new HashMap<String, Object>();// 返回数据集
		// 获得因子信息
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mnList);
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		// 站点集合
		ResultEntity stationAllEntity = iStieMangementService.queryAllInfoByMn(queryCode);
		List<Map<String, Object>> stationAllInfo = ObjectMapperUtil.convertListMap(stationAllEntity);
		String stationLevel = stationAllInfo.get(0).get("targerWaterQuality") == null ? "0"
				: stationAllInfo.get(0).get("targerWaterQuality").toString();
		String stationName = stationAllInfo.get(0).get("stationName") == null ? ""
				: stationAllInfo.get(0).get("stationName").toString();
		int armLevel = !stationLevel.equals("0")
				? Integer.parseInt(WaterLevelUtils.exchangeWaterLevelToNumber(stationLevel))
				: 3;
		result.put("airmLevrl", stationLevel);// 目标水质等级
		result.put("time", startTime + "至" + endTime);// 时间段
		result.put("computingMethod", "比例法");// 分析方法
		// 调用多站数据方法
		// 查询单站点下因子code集合
		ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(queryCode);
		List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
		List<Map<String, Object>> dataResults = datasCenterMore(timeType, startTime, endTime, projectCodes, mnList);
		if (dataResults == null || dataResults.size() == 0) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(info);
		}
		List<WaterInstructionsDataDto> InstructionsList = new ArrayList<WaterInstructionsDataDto>();
		WaterInstructionsDataDto Instructions = new WaterInstructionsDataDto();// 计算水质等级封装类
		List<String> keyPollution = new ArrayList<String>();
		// String waterLevel =
		// WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
		for (Map<String, Object> dataResult : dataResults) {
			String code = dataResult.get("CODE") == null ? "" : dataResult.get("CODE").toString();
			String value = dataResult.get("VALUE") == null ? "" : dataResult.get("VALUE").toString();
			String projectName = "";
			String decimalDigits = "3";
			if (projectMap != null) {
				Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(code),
						Project.class);
				projectName = project.getProjectName();
				decimalDigits = project.getDecimalDigits();
			}
			value = ScaleUtil.sciCalProjectString(value, decimalDigits);// 数据修约
			ReflexUtil.setValue(Instructions, WaterInstructionsDataDto.class, code, String.class, value);
			Integer indexLevel = WaterQualityUtil.getWaterLevel(code, value);
			if (indexLevel != 0 && indexLevel > armLevel && !keyPollution.contains(projectName)) {
				keyPollution.add(projectName);
			} // 计算设置主要污染物
		}
		InstructionsList.add(Instructions);
		WaterQualityUtil.setWaterQuality(InstructionsList);
		String level = WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
		String waterQuality = WaterLevelUtils.calculateProject(level);
		result.put("waterQuality", waterQuality);// 水环境质量（优良等信息）
		String message = "水质概述：" + startTime + "至" + endTime + "," + stationName + "水质等级为" + level + "," + "主要污染物为"
				+ StringUtils.join(keyPollution, ",");
		info.put("data", result);
		info.put("message", message);
		return new ResultEntity(ResultStatus.SUCCESS, Constants.QUERY_SUCCESS).setInfo(info);
	}

}
